package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.errorprone.annotations.Var;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * description:订单模块的gataway网关的controller层业务
 * author:houzhitao@139.com
 */
@Slf4j
@RestController
@RequestMapping("/shopping")
@Api(tags = "OrderController", description = "商品订单控制层")
public class OrderController {
    private ObjectMapper objectMapper = new ObjectMapper();
    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    @Reference(timeout = 3000,check = false)
    OrderCoreService orderCoreService;

    @Reference(timeout = 3000,check = false)
    OrderQueryService orderQueryService;

    /**
     * 创建订单
     * 方法：post
     * 是否携带token：是
     */
    @RequestMapping(value = "/order",method = {RequestMethod.POST})
    public ResponseData createOrder(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest){
        //获取用户token携带的userId
        String userInfo = (String)servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        //封装请求参数
        request.setUserId(uid);
        request.setUniqueKey(UUID.randomUUID().toString());
        //返回参数中封装的只有一个orderId
        CreateOrderResponse response = orderCoreService.createOrder(request);
        String orderId = response.getOrderId();
        if(orderId==null || "".equals(orderId)){
            return new ResponseUtil<String>().setErrorMsg("数据保存异常");
        }
        return new ResponseUtil<String>().setData(orderId,"success");
    }

    /**
     * 查询所有订单的方法
     * 方法：get
     * 是否携带token：是
     * @param
     * @return
     */
    @GetMapping("/order")
    public ResponseData getOrderList(
            @RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
            @RequestParam(value = "size", defaultValue = "10", required = false) Integer size,
            @RequestParam(value = "sort", required = false) String sort,HttpServletRequest servletRequest
    ){
        //从request域获取uid
        String userInfo =(String)servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        //请求参数封装
        OrderListRequest request = new OrderListRequest();
        request.setUserId(uid);
        request.setPage(page);
        request.setSize(size);
        request.setSort(sort);
        OrderListResponse orderListResponse=orderQueryService.queryOrderList(request);

        System.out.println("查询所有订单已输出到返回controller层"+orderListResponse);
        return new ResponseUtil<OrderListResponse>().setData(orderListResponse,"success");
    }

    /**
     * 查询对应订单的详情
     * 方法：get
     * 是否携带token：是
     * @return
     */
    @GetMapping("/order/{id}")
    public ResponseData getOrderDetail(@PathVariable("id") String id){
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
        orderDetailRequest.setOrderId(id);
        OrderDetailSingleResponse response = orderQueryService.queryOrderDetail(orderDetailRequest);
        return new ResponseUtil<OrderDetailSingleResponse>().setData(response,"success");
    }


    /**
     * 取消订单
     * 方法：post
     * 是否携带token：是
     * @param cancelOrderRequest
     * @return
     */
    @RequestMapping(value = "/cancelOrder",method = {RequestMethod.POST})
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest cancelOrderRequest){
        //将状态修改为交易失败，并修改交易关闭时间，将订单商品关联表修改为库存已释放，更新时间
        //库存表中减去订单中商品的数量，并加入到库存数量
        cancelOrderRequest.requestCheck();
        CancelOrderResponse cance = orderCoreService.cancelOrder(cancelOrderRequest);
        return new ResponseUtil<CancelOrderResponse>().setData(cance,"success");
    }

    /**
     * 删除订单
     * 方法：delete
     * 是否携带token：是
     * @param
     * @return
     */
    @RequestMapping(value = "/order/{id}",method = {RequestMethod.DELETE})
    public ResponseData cancelOrder(@PathVariable("id") String id){
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();
        deleteOrderRequest.setOrderId(id);
        //如果订单状态是已完成或已取消，将状态修改为交易关闭，否则先取消订单，再删除订单操作
        deleteOrderRequest.requestCheck();
        DeleteOrderResponse deleteOrder = orderCoreService.deleteOrder(deleteOrderRequest);
        return new ResponseUtil<DeleteOrderResponse>().setData(deleteOrder,"success");
    }

}
